package com.xinpujing.caiji.util;

import com.xinpujing.caiji.service.Api68Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * http 工具类
 */
public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    public static String getString(String urlStr)throws SocketTimeoutException{
        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            //读等待五秒
            httpConn.setReadTimeout(1000 * 5);
            InputStream inputStream = httpConn.getInputStream();
            String xml = StreamUtils.copyToString(inputStream , Charset.forName("utf8"));
            return xml;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            throw  e; // for invoker to do
        }catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getStringWithUserAgent(String urlStr )throws SocketTimeoutException{
        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            //读等待五秒
            httpConn.setReadTimeout(1000 * 5);
            httpConn.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:73.0) Gecko/20100101 Firefox/73.0");
            InputStream inputStream = httpConn.getInputStream();
            String xml = StreamUtils.copyToString(inputStream , Charset.forName("utf8"));
            return xml;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            throw  e; // for invoker to do
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
